<?php
class Model_Db_Core extends GDB{
    
    private $tablename;
    private $designekt; 
    private $filter = array(); 
    private $show = array(); 
    private $offset;
    private $limit;
    private $sql;
    private $connection;
    public  $result;
    private $resultTyp = 1;
    private $columns;
    
    
    function __construct($tablename,$offset = 0,$limit = 1,$filter = array(),$show = array(), $designekt = false){
        $this->tablename = $tablename;
        $this->filter = $filter;
        $this->show = $show;
        $this->offset = $offset;
        $this->limit = $limit;
        $this->connection = self::startGDB();
        
        if($designekt){
            $this->getTableSettings($tablename);
        }else{
            $this->sql = $this->creatSelect();
            $this->connection->Select($this->sql); 
        }
    }
    function getSQLResult($tablename,$filter,$show,$offset = 0,$limit = 1){
        $tablename = Model_Db_Core::getTablename($tablename);
        
        self::__construct($tablename,$offset,$limit,$filter,$show,false);        
    }
    
    function setSqlManuel($sql){    
        $this->connection = self::startGDB();
        $this->connection->Select($sql); 
    }
    
    function setInsert($tablename){
        $tablename = Model_Db_Core::getTablename($tablename);
        
        self::__construct($tablename,0,1,array(),array(),true);        
    }
    public function writeToDb($update= false){
        if(!$update){
            $sql = $this->creatInsert();            
        }else{            
            $sql = $this->creatUpdate();  
        }
        try {      
            $this->connection->Select($sql);
            return true;
        } catch (DbError $e) {            
            return $e->code;
        }
    }
    public function getTablename($tablename){
        $tablename_exp = explode('_',$tablename,2);        
        $tablename_exp = strtolower($tablename_exp[1]);      
        
        return $tablename_exp;
    }
    private function creatUpdate(){
        $tmp = $this->value;
        $wherel = $this->where;
        end($tmp);
        end($wherel);
        $last = key($tmp); 
        $lastwhere = key($wherel);         
        if(!$this->where)
            throw new Exception("In Class: Db_$this->tablename Where clause dosen't exist");    
        
        $sql = "UPDATE ".$this->tablename." SET ";
        
        foreach($this->value as $key => $value){
            if(is_numeric($value)){                
                $sql .= $key." = ".$value." ";   
            }else{
                $sql .= $key." = '".$value."' ";                
            } 
            if($last != $key){
                $sql .= ", "; 
            }
        }
                
        $sql .= " WHERE ";
        
        foreach($this->where as $key => $where){
            if(is_numeric($where)){                
                $sql .= $key." = ".$where." ";   
            }else{
                $sql .= $key." = '".$where."' ";                
            }
            if($lastwhere != $key){
                $sql .= " and "; 
            }
        }     
        return $sql;
    }
    private function creatInsert(){
        $lastValue = end($this->columns);
        
        $sql = "INSERT INTO ".$this->tablename." ( ";
        
        foreach($this->columns as $key => $column){
            if($lastValue->Field != $column->Field){
                $sql .= "`$column->Field`,";
            }else{
                $sql .= "`$column->Field`)";
            }
        }
        
        $sql .= "VALUES (";
        foreach($this->columns as $key => $column){
                if(!array_key_exists($column->Field,$this->value)){
                    if($column->Default != '')
                    {
                        $this->value[$column->Field] = $column->Default;
                    }
                    elseif($column->Extra == "auto_increment")
                    {
                        $this->value[$column->Field] = "NULL";
                    }
                    elseif($column->Null == "YES")
                    {
                        $this->value[$column->Field] = "NULL";
                    }
                    else
                    {
                        throw new Exception("In Class: Db_$this->tablename Key: $column->Field dosen't exist");    
                    }
                }
                
            if(preg_match("/int\(([0-9]{1,5})\)/",$column->Type)){
                $sql .= $this->value[$column->Field];
            }elseif("timestamp" == $column->Type){
                $sql .= $this->value[$column->Field];
            }elseif("date" == $column->Type || "time" == $column->Type ){
                $sql .= $this->value[$column->Field];
            }elseif($column->Null == "YES" && $this->value[$column->Field] == "NULL"){
                $sql .= $this->value[$column->Field];
            }else{
                $sql .= "'".$this->value[$column->Field]."'";
            }
            
            if($lastValue->Field != $column->Field){
                $sql .= ", ";
            }else{
                $sql .= ");";
            }
        }
        return $sql;
    }
    private function creatSelect(){
        
        $lastSelect = end($this->show);
        $lastWhere  = end($this->filter);
        
        $sql = "SELECT ";
        if($this->show){
            foreach ($this->show as $select){
                if($lastSelect != $select){
                    $sql .= $select.", ";
                }else{
                    $sql .= $select." ";
                }
            }
        }else{
            $sql .= " * ";            
        }
        
        $sql .= "FROM ".$this->tablename. " WHERE ";
        if($this->filter){
            foreach ($this->filter as $key => $where){
                if(key($this->filter) != $key){                
                    if(!is_numeric($where)){
                    	$where = mysql_escape_string($where);
                        $where = "'$where'";
                    }
                    $sql .= $key."=".$where." AND ";
                }else{ 
                    if(!is_numeric($where)){
                    	$where = mysql_escape_string($where);
                        $where = "'$where'";
                    }          
                    $sql .= $key."=".$where." ";
                }
            }
        }else{
            $sql .= " 1 ";
        }
        
        $sql .= "LIMIT $this->offset, $this->limit";
        
        return $sql;
    }
    public function setResultTyp($type = 1) {
        $this->resultTyp = $type;
    }
    public function result($count = 0) {
        switch ($this->resultTyp){
            case 1:
                return $this->connection->fetchobject($count);
                break;
            case 2:
                 return $this->connection->fetcharray($count);
                break;
            case 3:
                 return $this->connection->fetchassoc($count);
                break;                
            case 4:
                 return $this->connection->fetchassoc($count);
                break;
        }
    }
    private function getTableSettings($tablename){
        $this->connection->Select("SHOW COLUMNS FROM $tablename"); 
        $this->columns = $this->result();
    }
    public function setSQL($sql){        
        $this->connection->Select($sql);
    }
    public function getLastInsertId(){
        return  mysql_insert_id();       
    }
}
?>